// import kaplay
import kaplay from "https://unpkg.com/kaplay@3001/dist/kaplay.mjs";

// Fixed game area dimensions
const GAME_WIDTH = 640;
const GAME_HEIGHT = 360;


// start kaplay
kaplay({
    title: "Piggy Runner",
    background: [20, 20, 20], // Sky blue background
    debug: true,
    debugKey: "d",
    width: GAME_WIDTH,
    height: GAME_HEIGHT,
    scale: 2, // Base resolution scaling
    letterbox: true, // Maintain aspect ratio with black bars
});

setGravity(640);

// Load sprites
loadSprite("dino", "assets/dino.png");
loadSprite("goldfly", "assets/goldfly.png");

scene("game", () => {

    // Sky blue color background
    add([
        rect(width(), height()),
        pos(0),
        color(135, 206, 235), // Sky blue color
    ])

    // Create the player character
    const dino = add([
        sprite("dino"),
        pos(80, 150), // Starting position
        area(), // Collision detection
        body({ jumpForce: 400 }), // Physics body with jump force
        "player" // Tag for collision
    ]);

    // ground platform
    add([
        rect(width(), 80),
        outline(2),
        pos(0, height() - 80),
        area(),
        // This game object also has isStatic, so our player won't be able to move pass this
        body({ isStatic: true }),
        color(34, 139, 34), // Forest green
        "ground"
    ]);

    // Jump on spacebar press
    onKeyPress("space", () => {
        if (dino.isGrounded()) {
            dino.jump();
        }
    });


    // Spawn goldfly
    function spawnGoldfly() {
        add([
            sprite("goldfly", { flipX: true }), // Horizontal flip
            scale(0.5), // Reduced size
            pos(width(), rand(180, 250)), // Random vertical position
            area({
                shape: new Rect(
                    vec2(4, 4), // Center the hitbox
                    80,
                    50
                ),
            }),
            "goldfly",
            { speed: 280 } // Movement speed
        ]);
    }

    // Spawn new goldfly every 2 seconds
    loop(1.5, () => {
        spawnGoldfly();
    });

    // Move goldflies left
    onUpdate("goldfly", (goldfly) => {
        goldfly.move(-goldfly.speed, 0);
        if (goldfly.pos.x < -goldfly.width) {
            destroy(goldfly); // Remove off-screen goldflies
        }
    });

    // Game over on collision
    dino.onCollide("goldfly", () => {
        go("lose");
    });
})

scene("lose", () => {
    add([
        text("Game Over!", {
            size: 48,
            align: "center",
        }),
        pos(center()),
        anchor("center"),
        color(255, 0, 0),
    ]);
    add([
        text("Press Space to restart", {
            size: 24,
            align: "center",
        }),
        pos(center().sub(0, -60)),
        anchor("center"),
        color(200, 200, 200),
    ]);
    // go back to game with space is pressed
    onKeyPress("space", () => go("game"));
    onClick(() => go("game"));
});

go("game");